<template>
  <div class="user-list">
    <el-card class="box-card header-box">
      <div class="box-title">
        <span>用户列表</span>
      </div>
      <div class="box-detail">
        <span> 用户列表，可以对用户进行管理 </span>
      </div>
      <div class="search">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="用户名称">
            <el-input v-model="searchForm.username" />
          </el-form-item>
          <el-form-item label="科室">
            <el-select
              v-model="searchForm.office"
              clearable
              placeholder="请选择科室"
            >
              <el-option
                v-for="(item, index) in offices"
                :label="item.name"
                :value="item.id"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态">
            <el-select
              v-model="searchForm.state"
              clearable
              placeholder="请选择用户状态"
            >
              <el-option
                v-for="(item, index) in states"
                :label="item.label"
                :value="item.value"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="info" @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleCreate">新建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <div class="user_table">
      <el-table
        v-if="tableData"
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="序号" width="180"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="mail" label="邮箱"></el-table-column>
        <el-table-column prop="office" label="科室"> </el-table-column>
        <el-table-column prop="enable" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enabled === true">启用</el-tag>
            <el-tag v-else type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色">
          <template slot-scope="scope">
            <el-tag
              v-for="(role, index) in scope.row.roles"
              :key="index + role.id"
              size="mini"
              style="margin-right: 8px"
              type="success"
            >
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="page" label="权限板块"></el-table-column>
        <el-table-column prop="right" label="权限"></el-table-column>
        <el-table-column label="编辑">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="showEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              v-show="loginUserId == 55"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无数据"></el-empty>
      <user-edit
        :dialogVisible="dialogVisible"
        :title="title"
        :userData="userData"
        @submit="submit"
        @closeDialog="closeDialog"
        :type.sync="type"
        :userId="userId"
      />
      <pagination
        :total="total"
        :page-size.sync="queryParams.pageSize"
        :limit.sync="queryParams.limit"
        :layout="layout"
        @pagination="getData"
      >
      </pagination>
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import UserEdit from "./UserEdit.vue";
import { postRequest } from "@/api/api";
import { getRequest } from "@/api/api";
import store from "../../store";
export default {
  components: { Pagination, UserEdit },
  data() {
    return {
      loading: false,
      type: "create",
      tableData: [],
      total: 0,
      offices: store.getters.offices,
      layout: "total, prev, pager, next",
      userId: -1,
      loginUserId: store.getters.loginUser.data.id,
      userData: {},
      dialogVisible: false,
      title: "用户管理",
      states: [
        {
          value: "1",
          label: "启用",
        },
        {
          value: "0",
          label: "停用",
        },
        {
          value: "-1",
          label: "全部",
        },
      ],
      queryParams: {
        username: "",
        office: "",
        state: "-1",
        currentPageNum: 1,
        pageSize: 10,
        limit: 10,
      },
      searchForm: {
        username: "",
        office: "",
        state: "-1",
        currentPageNum: 1,
        pageSize: 10,
        limit: 10,
      },
      // form: {
      //   password: "123456",
      //   enabled: 1,
      // },
    };
  },
  created() {
    console.log(this.loginUserId);
    this.userListPost(this.queryParams);
  },
  methods: {
    handleCreate() {
      this.userId = -1;
      this.dialogVisible = true;
      this.type = "create";
    },
    handleEdit(index, row) {
      this.type = "edit";
      this.userData = row;
      this.userId = row.id;
      this.dialogVisible = true;
    },
    handleSearch() {
      this.userListPost(this.searchForm);
    },
    handleReset() {
      (this.searchForm.username = ""),
        (this.searchForm.office = ""),
        (this.searchForm.state = "-1"),
        this.userListPost(this.searchForm);
    },
    handleDelete(id) {
      var _this = this;
      this.$confirm("此操作将会删除该用户，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getRequest("/user/delete/" + id).then((resp) => {
          if (resp.status == 200) {
            if (resp.data.code === 1000) {
              _this.$message({ type: "success", message: "删除成功" });
              _this.userListPost(this.queryParams);
            } else {
              _this.$message({ type: "error", message: "删除失败" });
            }
          }
        });
      });
    },
    showEdit(user) {
      let result = user.roles.some((item) => item.name === "超级管理员");
      if (user.id == this.loginUserId) {
        result = false;
      }
      return !result;
    },
    userListPost(params) {
      this.loading = true;
      let url = "/user/list";
      postRequest(url, params)
        .then((res) => {
          if (res.status == 200) {
            let data = res.data.data;
            if (data.totalCount == 0) {
              this.total = data.totalCount;
              this.tableData = data.records;
              this.$message.info("暂无数据");
              this.loading = false;
              return;
            }
            this.total = data.totalCount;
            this.queryParams.currentPageNum = data.currrenPageNum;
            this.tableData = data.records;
            console.log("tableData:", this.tableData);
            for (let i = 0; i < this.tableData.length; i++) {
              for (let j = 0; j < this.offices.length; j++) {
                if (this.tableData[i].office == this.offices[j].id) {
                  this.tableData[i].office = this.offices[j].name;
                }
              }
            }
            this.loading = false;
          }
        })
        .catch((err) => {
          this.$message.error(err);
          this.loading = false;
        });
    },
    submit(val) {
      console.log(val);
      console.log(this.type);
      delete val.roles;
      delete val.gmtCreate;
      delete val.gmtModified;
      if (this.type == "create") {
        postRequest("/reg", val)
          .then((res) => {
            if (res.status == 200) {
              if (res.data.code == 1000) {
                this.dialogVisible = false;
                this.$message.success("添加成功");
                this.userListPost(this.queryParams);
              } else if (res.data.code == 1001) {
                this.$message.error(res.data.data);
              }
            } else {
              this.$message.error(res.data.data);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else if (this.type == "edit") {
        postRequest("/user/update", val).then((res) => {
          console.log(res);
          if (res.status == 200) {
            if (res.data.code == 1000) {
              this.dialogVisible = false;
              this.$message.success("更新成功");
              console.log(this.queryParams);
              this.userListPost(this.queryParams);
            } else if (res.data.code == 1001) {
              this.$message.error(res.data.data);
            }
          } else {
            this.$message.error(res.data.data);
          }
        });
      }
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    getData(val) {
      console.log(val);
      this.userListPost(val);
    },
  },
};
</script>

<style scoped>
.user-list {
  margin: 40px auto;
}
.search {
  text-align: right;
}
.el-form-item {
  margin: 0 15px;
}
.header-box {
  margin-bottom: 16px;
  padding: 24px;
}
.box-title {
  text-align: left;
  font-size: 20px;
}
.box-detail {
  text-align: left;
  color: gray;
  font-size: 14px;
}
</style>